package cn.itcast.utils;

import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * jdbc工具类
 *
 */
public class JDBCUtil {
    private static String driver;
    private static String url;
    private static String username;
    private static String password;
    private static Connection conn;
    private JDBCUtil(){//

    }

    static {

        try {
            //读取配置文件
            InputStream is = JDBCUtil.class.getClassLoader().getResourceAsStream("db.properties");
            //创建properties对象
            Properties prop = new Properties();
            prop.load(is);

            //给成员变量赋值
             driver = prop.getProperty("driver");
             url = prop.getProperty("url");
             username = prop.getProperty("username");
             password = prop.getProperty("password");

             //注册驱动
            Class.forName(driver);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    //获取连接
    public static Connection getConn(){
        try {
             conn = DriverManager.getConnection(url, username, password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }


    //释放资源,三个参数
    public static void close(Connection conn, Statement st, ResultSet rs){
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (st != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (rs != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }

    //释放资源,两个参数
    public static void close(Connection conn, Statement st){
        close(conn,st,null);
    }

}
